<?php

namespace app\admin\controller;

use app\common\ApiBase;
use app\model\AdminToken;
use app\model\SystemAdmin;
use app\service\HomeService;
use support\Redis;
use support\Request;
use support\Response;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class Auth extends ApiBase
{
    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function login(Request $request): Response
    {
        $username = $request->post('username', '');
        $password = $request->post('password', '');
        if (empty($username) || empty($password)) return $this->apiFailed('账号或者密码错误');
        //        $captcha = $request->post('captcha', '');
        //        if (empty($captcha) || strlen($captcha) != 4) return $this->apiFailed('图形验证码格式错误');
        //        if (strtolower($captcha) !== $request->session()->get('captcha')) {
        //            $request->session()->delete('captcha');
        //            return $this->apiFailed('图形验证码错误');
        //        }
        $admin = SystemAdmin::where(['username' => $username])->find();
        if (empty($admin)) return $this->apiFailed('用户不存在');
        if (password_admin($password) != $admin->password) return $this->apiFailed('密码输入有误');
        if ($admin->status == 0) return $this->apiFailed('账号已被禁用');
        $admin->login_num += 1;
        $admin->save();
        $token = AdminToken::adminLoginToken($admin);
        return $this->apiSuccess(['token' => $token['token'] ?? '']);
    }

    public function captcha(): Response
    {
        $img_content = HomeService::instance()->setCaptcha();
        return response($img_content, 200, ['Content-Type' => 'image/jpeg']);
    }

    //退出登录
    public function out(Request $request): Response
    {
        $token = $request->header('Authorization-admin', '');

        $res = Redis::set(ADMIN_TOKEN_LOGIN . $token, [], 'EX', 1, 1);

        return $res ? $this->apiSuccess() : $this->apiFailed();
    }

}